﻿@model List<Entity.NumberingRule>
@using System.Linq
@using Microsoft.AspNetCore.Mvc.Rendering
@{
    ViewData["Title"] = "编号规则管理";
}

<!-- 搜索区域 -->
<div class="row mb-4">
    <div class="col-md-2">
        <label for="TargetID" class="form-label">目标表单</label>
        <select class="form-select" id="TargetID">
            <option value="">请选择</option>
            @if (ViewBag.TargetForms != null)
            {
                var targetFormItems = ViewBag.TargetForms as List<SelectListItem>;
                if (targetFormItems != null && targetFormItems.Any())
                {
                    @foreach (var form in targetFormItems)
                    {
                        <option value="@form.Value">@form.Text</option>
                    }
                }
                else
                {
                    <option value="-1" disabled>无目标表单数据</option>
                }
            }
            else
            {
                <option value="-1" disabled>无目标表单数据</option>
            }
        </select>
    </div>
    <div class="col-md-3">
        <label for="NumberPrefix" class="form-label">编号前缀</label>
        <input type="text" class="form-control" id="NumberPrefix" placeholder="例如：HP">
    </div>
    <div class="col-md-3">
        <label for="TimeRule" class="form-label">时间规则</label>
        <input type="text" class="form-control" id="TimeRule" placeholder="例如：YYYYMM">
    </div>
    <div class="col-md-3">
        <label for="OperationTime" class="form-label">操作时间</label>
        <input type="datetime-local" class="form-control" id="OperationTime">
    </div>
    <div class="col-md-1 mt-4 d-flex align-items-end">
        <button type="button" class="btn btn-secondary me-2" id="resetBtn">重置</button>
        <button type="button" class="btn btn-success" id="queryBtn">查询</button>
    </div>
</div>

<!-- 功能按钮区域 -->
<div class="row mb-4">
    <div class="col-auto">
        <button type="button" class="btn btn-primary" id="exportBtn">导出</button>
    </div>
</div>

<!-- 数据表格区域 -->
<table class="table table-striped table-bordered table-hover">
    <thead class="table-light">
        <tr>
            <th><input type="checkbox" id="checkAll"></th>
            <th>序号</th>
            <th>目标表单</th>
            <th>编号前缀</th>
            <th>时间规则</th>
            <th>流水号位数</th>
            <th>步长</th>
            <th>生成规则预览</th>
            <th>操作人</th>
            <th>操作时间</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody id="ruleTableBody">
        @if (Model != null && Model.Count > 0)
        {
            for (int i = 0; i < Model.Count; i++)
            {
                var rule = Model[i];
                // 提前获取当前规则对应的目标表单Value（用于传递给编辑页）
                var targetFormValue = ViewBag.TargetForms != null
                ? (ViewBag.TargetForms as List<SelectListItem>).FirstOrDefault(f => f.Text == rule.TargetForm)?.Value ?? ""
                : "";
                <tr>
                    <td><input type="checkbox" class="ruleCheck" value="@rule.RuleID"></td>
                    <td>@(i + 1)</td>
                    <td>@rule.TargetForm</td>
                    <td>@rule.NumberPrefix</td>
                    <td>@rule.TimeRule</td>
                    <td>@rule.SerialNumber</td>
                    <td>@rule.Step</td>
                    <td>@rule.NumberProductionRule</td>
                    <td>@rule.Operator</td>
                    <td>@rule.OperationTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                    <!-- 编辑按钮：新增data-targetform（名称）和data-targetformvalue（值） -->
                    <td>
                        <a href="javascript:;" class="text-success edit-btn"
                           data-ruleid="@rule.RuleID"
                           data-targetform="@rule.TargetForm"
                           data-targetformvalue="@targetFormValue">
                            编辑
                        </a>
                    </td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="11" class="text-center py-3">暂无数据</td>
            </tr>
        }
    </tbody>
</table>

<!-- 右侧弹出的编辑模态框（初始隐藏） -->
<div class="modal right fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- 模态框头部 -->
            <div class="modal-header">
                <h5 class="modal-title" id="editModalLabel">编辑编号规则</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <!-- 模态框内容（通过AJAX加载部分视图） -->
            <div class="modal-body" id="editModalBody">
                <!-- 加载中提示 -->
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载编辑表单...</p>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        $(function () {
            // 1. 页面加载时初始化查询
            queryRules();

            // 2. 按钮事件绑定
            $("#queryBtn").click(queryRules); // 查询按钮
            $("#resetBtn").click(resetQuery); // 重置按钮
            $("#checkAll").change(checkAll); // 全选按钮

            // 3. 编辑按钮点击事件：传递规则ID+目标表单信息
            $(document).on("click", ".edit-btn", function () {
                const ruleId = $(this).data("ruleid");
                const targetForm = $(this).data("targetform"); // 从首页获取目标表单名称
                const targetFormValue = $(this).data("targetformvalue"); // 从首页获取目标表单值
                loadEditForm(ruleId, targetForm, targetFormValue); // 传递所有参数
            });
        });

        // 重置查询条件
        function resetQuery() {
            $("#TargetID").val("");
            $("#NumberPrefix").val("");
            $("#TimeRule").val("");
            $("#OperationTime").val("");
        }

        // 全选/取消全选
        function checkAll() {
            const isChecked = $(this).prop("checked");
            $(".ruleCheck").prop("checked", isChecked);
        }

        // 查询规则数据
        function queryRules() {
            const params = {
                TargetID: $("#TargetID").val() || null,
                NumberPrefix: $("#NumberPrefix").val(),
                TimeRule: $("#TimeRule").val(),
                OperationTime: $("#OperationTime").val()
            };

            $.post("/NumberingRule/Query", params)
                .done(function (res) {
                    if (!res.success) {
                        alert("查询失败：" + res.error);
                        return;
                    }
                    renderTable(res.data);
                })
                .fail(function (xhr) {
                    alert("请求错误：" + xhr.responseText);
                });
        }

        // 渲染表格数据
        function renderTable(data) {
            const tbody = $("#ruleTableBody").empty();
            if (!data || data.length === 0) {
                tbody.append('<tr><td colspan="11" class="text-center py-3">暂无数据</td></tr>');
                return;
            }

            data.forEach((rule, index) => {
                // 渲染时补充目标表单Value（用于编辑按钮数据）
                const targetFormValue = rule.targetFormValue || "";
                const tr = $(`
                    <tr>
                        <td><input type="checkbox" class="ruleCheck" value="${rule.ruleID}"></td>
                        <td>${index + 1}</td>
                        <td>${rule.targetForm || '-'}</td>
                        <td>${rule.numberPrefix || '-'}</td>
                        <td>${rule.timeRule || '-'}</td>
                        <td>${rule.serialNumber}</td>
                        <td>${rule.step}</td>
                        <td>${rule.numberProductionRule || '-'}</td>
                        <td>${rule.operator || '-'}</td>
                        <td>${rule.operationTime ? new Date(rule.operationTime).toLocaleString() : '-'}</td>
                        <td>
                            <a href="javascript:;" class="text-success edit-btn"
                               data-ruleid="${rule.ruleID}"
                               data-targetform="${rule.targetForm || ''}"
                               data-targetformvalue="${targetFormValue}">
                                编辑
                            </a>
                        </td>
                    </tr>
                `);
                tbody.append(tr);
            });
        }

        // 加载编辑表单：接收首页传递的目标表单参数
        function loadEditForm(ruleId, targetForm, targetFormValue) {
            // 用encodeURIComponent处理中文/特殊字符，避免乱码
            const encodedTargetForm = encodeURIComponent(targetForm || "");
            const encodedTargetFormValue = encodeURIComponent(targetFormValue || "");

            $.get(`/NumberingRule/EditPartial?ruleId=${ruleId}&targetForm=${encodedTargetForm}&targetFormValue=${encodedTargetFormValue}`)
                .done(function (html) {
                    // 填充模态框内容并显示
                    $("#editModalBody").html(html);
                    const modal = new bootstrap.Modal(document.getElementById("editModal"));
                    modal.show();
                })
                .fail(function (xhr) {
                    $("#editModalBody").html(`
                        <div class="alert alert-danger" role="alert">
                            加载编辑表单失败：${xhr.responseText}
                        </div>
                    `);
                });
        }

        // 保存成功后刷新表格（供编辑表单调用）
        function refreshTable() {
            queryRules();
        }
    </script>
}